package com.example.algorithm.sort.bubbling;

/**
 * @program: algorithm
 * @description: 冒泡算法
 * @packagename: com.example.algorithm.sort.bubbling
 * @author: Jay
 * @date: 2022/03/24 14:33:03
 **/
public class Bubble {
    /**
     * 对数组进行排序
     */
    public static void sort(Comparable[] a){

        for (int i = a.length-1; i > 0; i--) {
            for (int j = 0; j < i; j++){
                //比较索引j和j+1的值
                //n,n-1,n-2...2,1,     O(n^2)
                if (greater(a[j],a[j+1])){
                    exch(a,j,j+1);
                }
            }
        }

    }

    /**
     * 比较a>b
     */
    public static boolean greater(Comparable a, Comparable b){
        return a.compareTo(b)>0;
    }

    /**
     * 数组元素i，j交换位置
     */
    private static void exch(Comparable[] a, int i, int j){
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
